package com.stlm2.controller;

import com.stlm2.core.common.page.PageView;
import com.stlm2.dems.entity.*;
import com.stlm2.dems.service.IntegralGoodsService;
import com.stlm2.dems.service.PeriodsService;
import com.stlm2.dems.service.UserService;
import com.stlm2.util.codecontent.CodeContent;
import com.sun.tools.javac.jvm.Code;
import org.apache.commons.lang.math.NumberUtils;
import org.json.JSONObject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Author：fuchunyu
 * Date：2017/12/20
 * Description：积分商品控制器
 */
@Controller
@RequestMapping("/integralGoods")
public class IntegralGoodsController {

    @Resource
    private UserService userService;
    @Resource
    private IntegralGoodsService integralGoodsService;
    @Resource
    private PeriodsService periodsService;

    //积分商品列表页
    @RequestMapping("/list.json")
    public String list() {
        return "/integralGoods/list";
    }

    /*zlq
* crm添加商品页面
* */
    @RequestMapping(value="/addView",produces="application/json;charset=UTF-8")
    public ModelAndView addView(ModelAndView modelAndView){
        modelAndView.setViewName("/integralGoods/add");
        return modelAndView;
    }

    /*zlq
* crm商品详情页面
* */
    @RequestMapping(value="/detailsView",produces="application/json;charset=UTF-8")
    public ModelAndView detailsView(ModelAndView modelAndView,String id){
        modelAndView.setViewName("/integralGoods/details");
        modelAndView.addObject("id",id);
        return modelAndView;
    }

    /**
     * @param page   页数
     * @param token	用户标识
     * @param name	商品名称
     * @param state	商品状态
     * @return 积分商品查询
     */
    @ResponseBody
    @RequestMapping(value = "/search.json", produces = "application/json;charset=utf-8")
    public String search(ModelMap model, String page, String token, String name, Integer state) {

        int pageNo = 1;
        int pageSize = 20;
        if (NumberUtils.isDigits(page) && !"0".equals(page.trim())) {
            pageNo = NumberUtils.toInt(page);
        }
        if (StringUtils.isEmpty(token)) {
            return CodeContent.returnLogin();
        }
        User loginUser = userService.getByToken(token);
        if (loginUser == null) {
            return CodeContent.returnLogin();
        }
        IntegralGoods integralGoods = new IntegralGoods();

        if (!StringUtils.isEmpty(name)) {
            integralGoods.setName(name.trim());
        }

        if (!StringUtils.isEmpty(state)) {
            integralGoods.setState(state);
        }
        PageView pageview = integralGoodsService.getPage(pageNo, pageSize, integralGoods);
        if (pageview != null) {
            model.put("datas", integralGoodsService.convertModel(pageview.getRecords()));
            model.put("recordsTotal", pageview.getRowCount());
            model.put("totalPage", pageview.getPageCount());
            model.put("pageNow", pageview.getPageNow());
            model.put("code",1);
            model.put("msg","success");
        }
        return new JSONObject(model).toString();
    }

    /**
     * @param abbreviation    商品描述
     * @param name	商品名称
     * @param mainImg	商品主图
     * @param detailsImg	    商品详情图
     * @param token   用户标识
     * @param totalInventory   总库存
     * @param unitIntegral     积分单价
     * @param totalIntegral     积分总价（当商品类型为2的时间需要，为1的时候不需要）
     * @param goodsTypeValue    积分商品类型（1.积分兑换商品2.积分投资商品）
     * @return 添加积分商品
     */
    @ResponseBody
    @RequestMapping(value = "/add.json", produces = "application/json;charset=utf-8")
    public String add(String abbreviation, String name, String mainImg, String detailsImg, String token, Integer totalInventory, BigDecimal unitIntegral, BigDecimal totalIntegral, Integer goodsTypeValue,Integer state) {

        User user = userService.getByToken(token);
        if (user == null)
            return CodeContent.returnLogin();

        if (StringUtils.isEmpty(abbreviation))
            return CodeContent.returnFailure("描述不能为空！");
        if (StringUtils.isEmpty(name))
            return CodeContent.returnFailure("商品名称不能为空！");
        if (StringUtils.isEmpty(mainImg))
            return CodeContent.returnFailure("商品主图不能为空！");
        if (StringUtils.isEmpty(detailsImg))
            return CodeContent.returnFailure("商品详情不能为空！");
        if (StringUtils.isEmpty(totalInventory))
            return CodeContent.returnFailure("总库存不能为空！");
        if (StringUtils.isEmpty(unitIntegral))
            return CodeContent.returnFailure("单价积分不能为空！");
        if (StringUtils.isEmpty(goodsTypeValue))
            return CodeContent.returnFailure("商品类型不能为空！");
        if(StringUtils.isEmpty(state))
            return CodeContent.returnFailure("商品状态不能为空！");
        IntegralGoods integralGoods = new IntegralGoods();
        integralGoods.setAbbreviation(abbreviation);
        integralGoods.setName(name);
        integralGoods.setCreateTime(new Date());
        integralGoods.setCreateUserId(user.getId());
        integralGoods.setMainImg(mainImg);
        integralGoods.setDetailsImg(detailsImg);
        integralGoods.setGoods_type(GoodsType.getByIntValue(goodsTypeValue));
        integralGoods.setTotalInventory(totalInventory);
        integralGoods.setInventory(totalInventory);
        integralGoods.setUnitIntegral(unitIntegral);
        integralGoods.setState(state);

        if (GoodsType.IntegralPrize.getIntValue() == goodsTypeValue) {
            if (StringUtils.isEmpty(totalIntegral))
                return CodeContent.returnSuccess("总人数不能为空！");
            integralGoods.setTotalIntegral(totalIntegral);
            integralGoodsService.addEntity(integralGoods);
            Periods periods=new Periods();
            periods.setCode(100001);
            periods.setCreateTime(new Date());
            periods.setGoodsId(integralGoods.getId());
            periods.setNowNum(0);
            periods.setState(integralGoods.getState());
            periods.setTotalNum(integralGoods.getTotalIntegral().intValue());
            periods.setUnitIntegral(integralGoods.getUnitIntegral());
            periodsService.addEntity(periods);
        }else {
            integralGoodsService.addEntity(integralGoods);
        }

        return CodeContent.returnSuccess(null);
    }

    /**
     * @param id    商品ID
     * @param abbreviation  商品描述
     * @param name  商品名称
     * @param mainImg  商品主图
     * @param detailsImg  商品详情
     * @param token  用户标识
     * @param unitIntegral  单价积分
     * @param totalIntegral  总积分
     * @param state   商品状态
     * @return 更新积分商品
     */
    @ResponseBody
    @RequestMapping(value = "/update.json", produces = "application/json;charset=utf-8")
    public String update(Integer id, String abbreviation, String name, String mainImg, String detailsImg, String token, BigDecimal unitIntegral, BigDecimal totalIntegral, Integer state,Integer inventory) {
        User user=userService.getByToken(token);
        if(user==null)
            return CodeContent.returnLogin();
        IntegralGoods integralGoods=integralGoodsService.findEntityById(id);
        if(integralGoods==null)
            return CodeContent.returnFailure("没有找到商品！");
        if(!StringUtils.isEmpty(abbreviation))
            integralGoods.setAbbreviation(abbreviation);
        if(!StringUtils.isEmpty(name))
            integralGoods.setName(name);
        if(!StringUtils.isEmpty(mainImg))
            integralGoods.setMainImg(mainImg);
        if(!StringUtils.isEmpty(detailsImg))
            integralGoods.setDetailsImg(detailsImg);
        if(!StringUtils.isEmpty(unitIntegral))
            integralGoods.setUnitIntegral(unitIntegral);
        if(!StringUtils.isEmpty(totalIntegral))
            integralGoods.setTotalIntegral(totalIntegral);
        if(!StringUtils.isEmpty(state))
            integralGoods.setState(state);
        if(!StringUtils.isEmpty(inventory))
            integralGoods.setInventory(inventory);
        //如果是有效商品并且是抽奖商品，判断是否有期数正在进行，没有则添加
        if(integralGoods.getState()==1&&integralGoods.getGoods_type().equals(GoodsType.IntegralPrize)){
            Periods params=new Periods();
            params.setGoodsId(integralGoods.getId());
            List<Periods> periodsList=periodsService.getList(-1,-1,params);
            Periods period=periodsList.get(0);
            //无效并且没有结算的
           if(period.getState()==0&&period.getEndTime()==null){
               period.setState(1);
               periodsService.updateEntity(period);
               //无效并且已经结算的
            }else if(period.getState()==0&&period.getEndTime()!=null) {
               Periods periods=new Periods();
               periods.setCode(period.getCode()+1);
               periods.setGoodsId(integralGoods.getId());
               periods.setCreateTime(new Date());
               periods.setNowNum(0);
               periods.setState(integralGoods.getState());
               periods.setTotalNum(integralGoods.getTotalIntegral().intValue());
               periods.setUnitIntegral(integralGoods.getUnitIntegral());
               periodsService.addEntity(periods);
           }
        }
        integralGoods.setUpdateTime(new Date());
        integralGoods.setUpdateUserId(user.getId());
        integralGoodsService.updateEntity(integralGoods);
        return CodeContent.returnSuccess(null);
    }

    /**
     *
     * @param token  用户标识
     * @param id   商品标识
     * @param inventory  库存
     * @return  添加积分商品库存
     */
    @ResponseBody
    @RequestMapping(value = "/addInventory.json", produces = "application/json;charset=utf-8")
    public String addInventory(String token,Integer id,Integer inventory){
        User user=userService.getByToken(token);
        if(user==null)
            return CodeContent.returnLogin();
        IntegralGoods integralGoods=integralGoodsService.findEntityById(id);
        if(integralGoods==null)
            return CodeContent.returnFailure("没有找到商品！");
        if(inventory==null||inventory<=0)
            return CodeContent.returnFailure("请检查需要添加的库存！");
        integralGoods.setTotalInventory(integralGoods.getTotalInventory()+inventory);
        integralGoods.setInventory(integralGoods.getInventory()+inventory);
        integralGoodsService.updateEntity(integralGoods);
        return CodeContent.returnSuccess(null);
    }

    /**
     *
     * @param id   商品ID
     * @param token  用户标识
     * @return  订单详情
     */
    @ResponseBody
    @RequestMapping(value = "/detail.json", produces = "application/json;charset=utf-8")
    public String detail(Integer id,String token){
        User user=userService.getByToken(token);
        if(user==null)
            return CodeContent.returnLogin();
        IntegralGoods integralOrder=integralGoodsService.findEntityById(id);
        if(integralOrder==null)
            return CodeContent.returnFailure("订单查询失败！");
        ModelMap modelMap=integralGoodsService.buildModel(integralOrder);
        return CodeContent.returnSuccess(modelMap);
    }

}
